<template>
  <div class="payment-detail-page">
    <el-card>
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="goBack" icon="ArrowLeft" type="text">返回</el-button>
        <h2 class="page-title">支付明细</h2>
      </div>
      
      <!-- 会员信息 -->
      <div class="member-info">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="会员ID">{{ memberInfo.id }}</el-descriptions-item>
          <el-descriptions-item label="会员昵称">{{ memberInfo.nickname }}</el-descriptions-item>
          <el-descriptions-item label="当前余额">{{ memberInfo.balance }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 搜索栏 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" size="small">
          <el-form-item label="支付类型">
            <el-select v-model="searchForm.paymentType" placeholder="全部" clearable style="width: 150px;">
              <el-option label="充值" value="recharge" />
              <el-option label="扣款" value="deduction" />
            </el-select>
          </el-form-item>

          <el-form-item label="付款渠道">
            <el-select v-model="searchForm.paymentChannel" placeholder="全部" clearable style="width: 150px;">
              <el-option label="支付宝" value="alipay" />
              <el-option label="微信支付" value="wechat" />
              <el-option label="银行卡" value="bank" />
              <el-option label="PayPal" value="paypal" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 150px;">
              <el-option label="成功" value="success" />
              <el-option label="失败" value="failed" />
              <el-option label="处理中" value="pending" />
              <el-option label="已撤销" value="revoked" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付日期">
            <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始" end-placeholder="结束" style="width: 240px;" />
          </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
        </el-form>
      </div>

      <!-- 支付汇总统计 -->
      <div class="payment-summary" style="margin: 16px 0; padding: 16px; background: #f5f7fa; border-radius: 8px;">
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="summary-item">
              <div class="summary-label">充值总金额</div>
              <div class="summary-value recharge-total">¥{{ totalRechargeAmount.toLocaleString() }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="summary-item">
              <div class="summary-label">扣款总金额</div>
              <div class="summary-value deduction-total">¥{{ totalDeductionAmount.toLocaleString() }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="summary-item">
              <div class="summary-label">当前余额</div>
              <div class="summary-value current-balance">¥{{ currentBalance.toLocaleString() }}</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 支付记录表格 -->
      <el-table :data="pagedData" border stripe style="width: 100%; margin-top: 16px;">
        <el-table-column prop="id" label="记录ID" width="100" />
        <el-table-column prop="payment_type" label="类型" width="100">
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 4px;">
              <!-- 退款记录只显示退款标签 -->
              <el-tag v-if="scope.row.id.startsWith('REFUND')" type="warning">退款</el-tag>
              <!-- 撤销记录显示撤销标签 -->
              <el-tag v-else-if="scope.row.id.startsWith('REVERSE')" type="info">撤销</el-tag>
              <!-- 其他记录显示充值或扣款标签 -->
              <el-tag v-else :type="scope.row.payment_type === 'recharge' ? 'success' : 'danger'">
                {{ scope.row.payment_type === 'recharge' ? '充值' : '扣款' }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="scope">
            <span :class="scope.row.payment_type === 'recharge' ? 'amount-positive' : 'amount-negative'">
              {{ scope.row.payment_type === 'recharge' ? '+' : '-' }}{{ scope.row.amount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额" width="120">
          <template #default="scope">
            <span class="balance-positive">
              {{ scope.row.balance || '¥0' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="货币单位" width="100">
          <template #default="scope">
            <el-tag type="warning">JPY</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payment_channel" label="付款渠道" width="120">
          <template #default="scope">
            <el-tag type="primary">{{ getChannelName(scope.row.payment_channel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <div>
              <span>{{ scope.row.remark }}</span>
              <div v-if="scope.row.related_record_id" style="margin-top: 4px; display: flex; align-items: center; gap: 4px;">
                <el-tag type="info" size="small">
                  关联: {{ scope.row.related_record_id }}
                </el-tag>
                <el-button 
                  type="primary" 
                  size="small" 
                  text 
                  @click="copyToClipboard(scope.row.related_record_id)"
                  style="padding: 2px 4px; min-width: unset;"
                >
                  <el-icon><CopyDocument /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payment_date" label="支付日期" width="160" />
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div style="display: flex; gap: 4px;">
              <el-button size="small" @click="viewDetail(scope.row)">查看明细</el-button>
              <el-button 
                v-if="canRevoke(scope.row)"
                size="small" 
                type="danger" 
                @click="revokePayment(scope.row)"
                :disabled="scope.row.status !== 'success'"
              >
                撤销
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 16px; text-align: right;">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 查看明细弹窗 -->
    <el-dialog v-model="showDetailDialog" title="支付明细" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="支付类型">
          <div style="display: flex; align-items: center; gap: 4px;">
            <el-tag :type="detailData.payment_type === 'recharge' ? 'success' : 'danger'">
              {{ detailData.payment_type === 'recharge' ? '充值' : '扣款' }}
            </el-tag>
            <el-tag v-if="detailData.id && detailData.id.startsWith('REFUND')" type="warning" size="small">退款</el-tag>
            <el-tag v-if="detailData.id && detailData.id.startsWith('REVERSE')" type="info" size="small">撤销</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="金额">{{ detailData.amount }}</el-descriptions-item>
        <el-descriptions-item label="货币单位">
          <el-tag type="warning">JPY</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="付款渠道">{{ getChannelName(detailData.payment_channel) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusName(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="支付日期" :span="2">{{ detailData.payment_date }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          <div>
            <span>{{ detailData.remark || '无' }}</span>
            <div v-if="detailData.related_record_id" style="margin-top: 8px; display: flex; align-items: center; gap: 8px;">
              <el-tag type="info" size="small">
                关联记录: {{ detailData.related_record_id }}
              </el-tag>
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="copyToClipboard(detailData.related_record_id)"
                style="padding: 4px 8px; min-width: unset;"
              >
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="交易流水号" :span="2">{{ detailData.transaction_id }}</el-descriptions-item>
        <el-descriptions-item label="操作人" :span="2">{{ detailData.operator || '系统' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ detailData.create_time }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, CopyDocument } from '@element-plus/icons-vue'
import { getPaymentRecordsAPI, savePaymentRecordAPI } from '@/services/api'
import { getMockPaymentRecords } from '@/mock/paymentRecords'
import type { PaymentRecord } from '@/services/database'

const route = useRoute()
const router = useRouter()

// 会员信息
const memberInfo = ref({
  id: route.params.id as string,
  nickname: route.params.nickname as string,
  balance: '¥123,456'
})

// 搜索表单
const searchForm = ref({
  paymentType: '',
  paymentChannel: '',
  status: '',
  dateRange: []
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 从数据库获取支付记录数据
const generatePaymentRecords = async (): Promise<PaymentRecord[]> => {
  const memberId = route.params.id as string
  console.log('正在获取会员ID:', memberId, '类型:', typeof memberId)
  
  try {
    // 优先使用 Mock 模式
    const isMock = ((): boolean => {
      const flag = localStorage.getItem('mockPayments')
      return flag === '1' || /[?&]mock=1(&|$)/.test(window.location.search)
    })()
    if (isMock) {
      const mock = getMockPaymentRecords(memberId)
      console.log('使用Mock支付记录，条数:', mock.length)
      if (mock.length > 0) return mock
      // 没有则返回固定测试数据
      return createFixedTestData()
    }

    // 从数据库获取记录
    const dbRecords = await getPaymentRecordsAPI(memberId)
    console.log('数据库返回记录数:', dbRecords.length)
    
    // 调试：打印数据库中的记录详情
    if (dbRecords.length > 0) {
      console.log('数据库中的记录详情:')
      dbRecords.forEach((record, index) => {
        console.log(`[${index}] ID: ${record.id}, 类型: ${record.payment_type}, 金额: ${record.amount}, 余额: ${record.balance}, 时间: ${record.payment_date}`)
      })
    }
    
    // 如果有数据库记录，使用数据库记录
    if (dbRecords.length > 0) {
      console.log(`从数据库获取到 ${dbRecords.length} 条支付记录`)
      return dbRecords
    }
    
    // 数据库中没有记录，使用Mock数据
    console.log('数据库中没有记录，使用Mock数据')
    return createFixedTestData()
  } catch (error) {
    console.error('获取支付记录失败:', error)
    return []
  }
}

// 创建固定的测试数据
function createFixedTestData(): PaymentRecord[] {
  const memberId = route.params.id as string
  const baseTime = new Date('2024-01-01 10:00:00').getTime()
  
  // 根据会员ID返回不同的测试数据（仅在mock关闭时兜底）
  if (memberId !== '10001' && memberId !== '10003') {
    // 其他用户：默认测试数据
    return [
      {
        id: 'PAY0001',
        member_id: memberId,
        payment_type: 'recharge',
        amount: '10000',
        balance: '¥10,000',
        currency: 'JPY',
        payment_channel: '扫码充值',
        remark: '初始充值',
        status: 'success',
        payment_date: new Date(baseTime).toLocaleString(),
        transaction_id: 'TXN001',
        create_time: new Date(baseTime).toLocaleString(),
        operator: '管理员',
        related_record_id: undefined,
        is_revoked: 0
      },
      {
        id: 'PAY0002',
        member_id: memberId,
        payment_type: 'deduction',
        amount: '2000',
        balance: '¥8,000',
        currency: 'JPY',
        payment_channel: '系统扣款',
        remark: '购买商品',
        status: 'success',
        payment_date: new Date(baseTime + 3600000).toLocaleString(),
        transaction_id: 'TXN002',
        create_time: new Date(baseTime + 3600000).toLocaleString(),
        operator: '系统',
        related_record_id: undefined,
        is_revoked: 0
      },
      {
        id: 'PAY0003',
        member_id: memberId,
        payment_type: 'recharge',
        amount: '5000',
        balance: '¥13,000',
        currency: 'JPY',
        payment_channel: '国际汇款',
        remark: '客户汇款',
        status: 'success',
        payment_date: new Date(baseTime + 7200000).toLocaleString(),
        transaction_id: 'TXN003',
        create_time: new Date(baseTime + 7200000).toLocaleString(),
        operator: '管理员',
        related_record_id: undefined,
        is_revoked: 0
      }
    ]
  }
  return []
}

const paymentRecords = ref<PaymentRecord[]>([])

// 初始化支付记录
onMounted(async () => {
  paymentRecords.value = await generatePaymentRecords()
  // 计算余额
  recalculateAllBalances()
})

// 不再提供手动刷新函数

// 过滤数据
const filteredData = computed(() => {
  const filtered = paymentRecords.value.filter(record => {
    // 支付类型
    if (searchForm.value.paymentType && record.payment_type !== searchForm.value.paymentType) return false
    // 付款渠道
    if (searchForm.value.paymentChannel && record.payment_channel !== searchForm.value.paymentChannel) return false
    // 状态
    if (searchForm.value.status && record.status !== searchForm.value.status) return false
    // 日期范围
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      const recordDate = new Date(record.payment_date).getTime()
      const [start, end] = searchForm.value.dateRange.map(v => new Date(v).getTime())
      if (recordDate < start || recordDate > end) return false
    }
    return true
  })
  
  // 按支付时间倒序排序
  return filtered.sort((a, b) => {
    const dateA = new Date(a.payment_date).getTime()
    const dateB = new Date(b.payment_date).getTime()
    return dateB - dateA // 倒序：最新的在前面
  })
})

// 分页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredData.value.slice(start, start + pageSize.value)
})

// 撤销相关计算属性
const revokedRecords = computed(() => {
  return paymentRecords.value.filter(record => record.status === 'revoked')
})

const successRecords = computed(() => {
  return paymentRecords.value.filter(record => record.status === 'success')
})

// 可撤销记录（30天内且状态为成功）
const revokableRecords = computed(() => {
  return paymentRecords.value.filter(record => {
    if (record.status !== 'success') return false
    
    const paymentDate = new Date(record.payment_date)
    const currentDate = new Date()
    const timeDiff = currentDate.getTime() - paymentDate.getTime()
    const daysDiff = timeDiff / (1000 * 3600 * 24)
    
    return daysDiff <= 30
  })
})

const revokedRate = computed(() => {
  if (paymentRecords.value.length === 0) return 0
  return Math.round((revokedRecords.value.length / paymentRecords.value.length) * 100)
})

const refundRecords = computed(() => {
  return paymentRecords.value.filter(record => record.id.startsWith('REFUND'))
})

const reverseRecords = computed(() => {
  return paymentRecords.value.filter(record => record.id.startsWith('REVERSE'))
})

const refundRate = computed(() => {
  if (paymentRecords.value.length === 0) return 0
  return Math.round((refundRecords.value.length / paymentRecords.value.length) * 100)
})

const reverseRate = computed(() => {
  if (paymentRecords.value.length === 0) return 0
  return Math.round((reverseRecords.value.length / paymentRecords.value.length) * 100)
})

// 充值总金额计算 - 统计所有有效的充值记录
const totalRechargeAmount = computed(() => {
  return paymentRecords.value
    .filter(r => r.payment_type === 'recharge' && r.status !== 'revoked')
    .reduce((sum, record) => sum + Number(record.amount), 0)
})

// 扣款总金额计算 - 统计所有有效的扣款记录
const totalDeductionAmount = computed(() => {
  return paymentRecords.value
    .filter(r => r.payment_type === 'deduction' && r.status !== 'revoked')
    .reduce((sum, record) => sum + Number(record.amount), 0)
})

// 当前余额计算
const currentBalance = computed(() => {
  return totalRechargeAmount.value - totalDeductionAmount.value
})

// 查看明细相关
const showDetailDialog = ref(false)
const detailData = ref<any>({})

function viewDetail(row: any) {
  detailData.value = row
  showDetailDialog.value = true
}

// 检查是否可以撤销（30天内）
function canRevoke(row: any): boolean {
  // 如果不是成功状态，不能撤销
  if (row.status !== 'success') {
    return false
  }
  
  // 检查是否在30天内
  const paymentDate = new Date(row.payment_date)
  const currentDate = new Date()
  const timeDiff = currentDate.getTime() - paymentDate.getTime()
  const daysDiff = timeDiff / (1000 * 3600 * 24)
  
  // 超过30天不能撤销
  return daysDiff <= 30
}

// 撤销支付
function revokePayment(row: any) {
  const isRefund = row.id.startsWith('REFUND')
  const isReverse = row.id.startsWith('REVERSE')
  const operationName = isRefund ? '退款' : (isReverse ? '撤销操作' : (row.payment_type === 'recharge' ? '充值' : '扣款'))
  
  // 检查撤销操作是否会导致余额为负数
  const recordIndex = paymentRecords.value.findIndex(r => r.id === row.id)
  if (recordIndex === -1) return
  
  // 计算撤销后的预期余额
  let expectedBalance = 0
  const sortedRecords = [...paymentRecords.value].sort((a, b) => {
    const dateA = new Date(a.payment_date).getTime()
    const dateB = new Date(b.payment_date).getTime()
    return dateA - dateB
  })
  
  // 模拟撤销操作后的余额（只计算撤销前的记录）
  let tempBalance = 0
  const revokeRecordDate = new Date(row.payment_date).getTime()
  
  for (let i = 0; i < sortedRecords.length; i++) {
    const record = sortedRecords[i]
    
    // 只计算撤销记录时间点之前的记录
    const recordDate = new Date(record.payment_date).getTime()
    if (recordDate > revokeRecordDate) continue
    
    // 跳过当前要撤销的记录
    if (record.id === row.id) continue
    
    // 移除跳过已撤销记录的判断，所有记录都参与计算
    
    const amount = Number(record.amount)
    
    if (record.payment_type === 'recharge') {
      tempBalance += amount
    } else if (record.payment_type === 'deduction') {
      tempBalance = Math.max(0, tempBalance - amount)
    }
  }
  
  // 计算撤销操作的影响
  const revokeAmount = Number(row.amount)
  let newExpectedBalance = tempBalance
  
  if (row.payment_type === 'recharge') {
    // 撤销充值 = 扣款
    newExpectedBalance = Math.max(0, tempBalance - revokeAmount)
  } else {
    // 撤销扣款 = 充值
    newExpectedBalance = tempBalance + revokeAmount
  }
  
  // 检查是否会为负数
  if (newExpectedBalance < 0) {
    ElMessageBox.alert(
      `撤销此${operationName}记录会导致会员余额变为负数（¥${newExpectedBalance}），无法撤销。`,
      '撤销失败',
      {
        confirmButtonText: '知道了',
        type: 'warning'
      }
    )
    return
  }
  
  ElMessageBox.confirm(
    `确定要撤销这笔${operationName}记录吗？撤销后将生成撤销操作记录。`,
    '确认撤销',
    {
      confirmButtonText: '确定撤销',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 执行撤销操作
    if (recordIndex !== -1) {
      // 在改变状态前，保存当前的正确余额（撤销前应该显示的余额）
      const originalBalance = paymentRecords.value[recordIndex].balance
      
      // 更新原记录状态为已撤销
      paymentRecords.value[recordIndex].status = 'revoked'
      paymentRecords.value[recordIndex].remark = (paymentRecords.value[recordIndex].remark || '') + ' (已撤销)'
      paymentRecords.value[recordIndex].is_revoked = 1
      
      // 保持原有余额显示，不设置为"-"
      paymentRecords.value[recordIndex].balance = originalBalance
      
      // 根据原记录类型确定撤销操作类型
      let reversePaymentType: 'recharge' | 'deduction'
      let reverseRemark: string
      
      if (row.payment_type === 'recharge') {
        // 充值撤销 -> 生成扣款记录
        reversePaymentType = 'deduction'
        reverseRemark = `撤销充值记录`
      } else {
        // 扣款撤销 -> 生成充值记录
        reversePaymentType = 'recharge'
        reverseRemark = `撤销扣款记录`
      }
      
      // 生成撤销记录
      // 使用当前时间作为撤销操作的时间
      const currentTime = new Date()
      
      const reverseRecord: PaymentRecord = {
        id: `REVERSE${String(100000 + paymentRecords.value.length).slice(1)}`,
        member_id: row.member_id,
        payment_type: reversePaymentType,
        amount: row.amount,
        balance: '',
        currency: 'JPY',
        payment_channel: row.payment_channel,
        remark: reverseRemark,
        status: 'success',
        // 使用当前时间，记录撤销操作发生的时间
        payment_date: currentTime.toLocaleString(),
        transaction_id: `TXN${Date.now()}`,
        create_time: currentTime.toLocaleString(),
        operator: '管理员',
        related_record_id: row.id,
        is_revoked: 0
      }

      // 直接插入原记录后方，保持时间顺序
      paymentRecords.value.splice(recordIndex + 1, 0, reverseRecord)
      
      // 重新计算所有记录的余额
      recalculateAllBalances()
      
              ElMessage.success(`撤销成功！已生成撤销操作记录`)
    }
  }).catch(() => {
    // 用户取消
  })
}

// 重新计算余额的函数
function recalculateBalances(startIndex: number) {
  let currentBalance = 0
  
  // 按支付时间升序排序，确保计算顺序正确
  const sortedRecords = [...paymentRecords.value].sort((a, b) => {
    const dateA = new Date(a.payment_date).getTime()
    const dateB = new Date(b.payment_date).getTime()
    return dateA - dateB // 升序：最早的在前
  })
  
  // 找到起始索引对应的时间点
  let startTime = 0
  if (startIndex > 0 && startIndex < sortedRecords.length) {
    startTime = new Date(sortedRecords[startIndex].payment_date).getTime()
  }
  
  // 重新计算所有记录的余额
  let balance = 0
  for (let i = 0; i < sortedRecords.length; i++) {
    const record = sortedRecords[i]
    
    // 跳过已撤销的记录
    if (record.status === 'revoked' && !record.id.startsWith('REVERSE')) {
      continue
    }
    
    const amount = Number(record.amount)
    
    if (record.payment_type === 'recharge') {
      balance += amount
    } else if (record.payment_type === 'deduction') {
      balance = Math.max(0, balance - amount)
    }
    
    // 更新记录的余额
    record.balance = `¥${balance.toLocaleString()}`
    
    // 更新原始数组中的对应记录
    const originalIndex = paymentRecords.value.findIndex(r => r.id === record.id)
    if (originalIndex !== -1) {
      paymentRecords.value[originalIndex].balance = record.balance
    }
  }
}

// 重新计算所有记录余额的函数
function recalculateAllBalances() {
  if (paymentRecords.value.length === 0) {
    memberInfo.value.balance = '¥0'
    return
  }
  
  // 获取所有有效记录（排除已撤销的记录）
  const validRecords = paymentRecords.value.filter(record => record.status !== 'revoked')
  
  // 按时间升序排序（最早的在前）
  const sortedRecords = validRecords.sort((a, b) => {
    const dateA = new Date(a.payment_date).getTime()
    const dateB = new Date(b.payment_date).getTime()
    return dateA - dateB
  })
  
  // 3. 计算每条记录的余额（修复REVERSE记录逻辑）
  let runningBalance = 0
  const recordsWithBalance = sortedRecords.map((record, index) => {
    const amount = Number(record.amount)
    
    // 特殊处理REVERSE记录 - 显示撤销前的余额状态
    if (record.id.startsWith('REVERSE')) {
      const balanceText = runningBalance >= 0 
        ? `¥${runningBalance.toLocaleString()}` 
        : `-¥${Math.abs(runningBalance).toLocaleString()}`
      

      
      return {
        ...record,
        balance: balanceText // 显示撤销前的余额状态
      }
    }
    
    // 普通记录的余额计算
    if (record.payment_type === 'recharge') {
      runningBalance += amount
    } else if (record.payment_type === 'deduction') {
      runningBalance -= amount
    }
    
    // 格式化余额显示
    const balanceText = runningBalance >= 0 
      ? `¥${runningBalance.toLocaleString()}` 
      : `-¥${Math.abs(runningBalance).toLocaleString()}`
    

    
    return {
      ...record,
      balance: balanceText
    }
  })
  
  // 4. 更新原始数组中的余额信息
  paymentRecords.value.forEach(originalRecord => {
    const updatedRecord = recordsWithBalance.find(r => r.id === originalRecord.id)
    if (updatedRecord) {
      originalRecord.balance = updatedRecord.balance
          } else if (originalRecord.status === 'revoked') {
        // 已撤销的记录保持原有余额，不设置为"-"
      }
  })
  
  // 5. 按时间倒序排序（最新的在前，用于显示）
  paymentRecords.value.sort((a, b) => {
    const dateA = new Date(a.payment_date).getTime()
    const dateB = new Date(b.payment_date).getTime()
    return dateB - dateA
  })
  
  // 6. 更新会员当前余额
  const finalBalance = recordsWithBalance.length > 0 
    ? recordsWithBalance[recordsWithBalance.length - 1].balance 
    : '¥0'
    
  memberInfo.value.balance = finalBalance
  console.log('✨ 计算完成，最终余额:', finalBalance)
}

// 工具函数
function getChannelName(channel: string) {
  const channelMap: Record<string, string> = {
    alipay: '支付宝',
    wechat: '微信支付',
    bank: '银行卡',
    paypal: 'PayPal',
    scan: '扫码充值',
    wire: '国际汇款',
    other: '其他',
    transfer: '转给好友',
    withdraw: '余额提现',
    '好友转账': '好友转账'
  }
  return channelMap[channel] || channel
}

function getStatusName(status: string) {
  const statusMap: Record<string, string> = {
    success: '成功',
    failed: '失败',
    pending: '处理中',
    revoked: '已撤销'
  }
  return statusMap[status] || status
}

function getStatusType(status: string) {
  const typeMap: Record<string, string> = {
    success: 'success',
    failed: 'danger',
    pending: 'warning',
    revoked: 'info'
  }
  return typeMap[status] || 'info'
}

// 搜索和重置
function onSearch() {
  currentPage.value = 1
}

function onReset() {
  searchForm.value = {
    paymentType: '',
    paymentChannel: '',
    status: '',
    dateRange: []
  }
  currentPage.value = 1
}

// 复制到剪贴板
async function copyToClipboard(text: string) {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('关联订单ID已复制到剪贴板')
  } catch (error) {
    // 降级方案：使用传统方法
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('关联订单ID已复制到剪贴板')
    } catch (err) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}

// 返回上一页
function goBack() {
  router.back()
}



onMounted(() => {
  // 页面初始化
})
</script>

<style scoped>
.payment-detail-page {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0 0 0 10px;
  font-size: 20px;
  font-weight: 600;
  flex: 1;
}

.member-info {
  margin-bottom: 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.amount-positive {
  color: #67c23a;
  font-weight: 600;
}

.amount-negative {
  color: #f56c6c;
  font-weight: 600;
}

.payment-summary {
  margin: 16px 0;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.summary-item {
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.summary-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.recharge-total {
  color: #67c23a;
}

.deduction-total {
  color: #f56c6c;
}

.current-balance {
  color: #409eff;
}

.balance-positive {
  color: #67c23a;
  font-weight: 600;
}

.balance-negative {
  color: #f56c6c;
  font-weight: 600;
}
</style> https://www.idora.jp/goods/q1176960852